Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
import platform
print(platform.python_version())

import tensorflow as tf
if tf.test.is_built_with_cuda():
    from tensorflow.python.client import device_lib

    local_device_protos = device_lib.list_local_devices()
    for x in local_device_protos:
        if x.device_type == 'GPU':
            print(x.physical_device_desc)
3.6.6
device: 0, name: GeForce GTX 1060 6GB, pci bus id: 0000:01:00.0, compute capability: 6.1
In [2]:
from sklearn.datasets import load_files
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [3]:
import random
# random.seed(8675309)
random.seed(7674308)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [4]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [5]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: 99% of pictures with human faces are correctly detected. lfw/Derek_Bond/Derek_Bond_0001.jpg picture is incorrectly classified as not containing face. I am not sure what the problem is. But he has glasses on.

11% of dog pictures are incorrectly classified as containing human face. Problem with picture dogImages/train/106.Newfoundland/Newfoundland_06989.jpg is that it really contains human face. Which makes it about 10%.

In [6]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
h_detected = 0
d_detected = 0
print("Length of human sample {}".format(str(len(human_files_short))))
print("Length of dog sample {}".format(str(len(dog_files_short))))
for img_path in human_files_short:
    if face_detector(img_path):
        h_detected += 1
    else:
        print("Human was not detected: {}".format(img_path))
        
for img_path in dog_files_short:
    if face_detector(img_path):
        d_detected += 1
        print("Human was detected in dog image: {}".format(img_path))
        
print("Percentage of detected human faces in human sample {}".format(str((h_detected/100.)*100.)))
print("Percentage of detected human faces in dog sample {}".format(str((d_detected/100.)*100.)))
Length of human sample 100
Length of dog sample 100
Human was not detected: lfw/Colin_Montgomerie/Colin_Montgomerie_0004.jpg
Human was not detected: lfw/Buddy_Ryan/Buddy_Ryan_0001.jpg
Human was not detected: lfw/Thor_Pedersen/Thor_Pedersen_0001.jpg
Human was not detected: lfw/John_Velazquez/John_Velazquez_0001.jpg
Human was detected in dog image: dogImages/train/095.Kuvasz/Kuvasz_06442.jpg
Human was detected in dog image: dogImages/train/099.Lhasa_apso/Lhasa_apso_06646.jpg
Human was detected in dog image: dogImages/train/009.American_water_spaniel/American_water_spaniel_00628.jpg
Human was detected in dog image: dogImages/train/057.Dalmatian/Dalmatian_04023.jpg
Human was detected in dog image: dogImages/train/096.Labrador_retriever/Labrador_retriever_06474.jpg
Human was detected in dog image: dogImages/train/106.Newfoundland/Newfoundland_06989.jpg
Human was detected in dog image: dogImages/train/117.Pekingese/Pekingese_07559.jpg
Human was detected in dog image: dogImages/train/039.Bull_terrier/Bull_terrier_02805.jpg
Human was detected in dog image: dogImages/train/097.Lakeland_terrier/Lakeland_terrier_06516.jpg
Human was detected in dog image: dogImages/train/057.Dalmatian/Dalmatian_04086.jpg
Human was detected in dog image: dogImages/train/024.Bichon_frise/Bichon_frise_01771.jpg
Human was detected in dog image: dogImages/train/084.Icelandic_sheepdog/Icelandic_sheepdog_05705.jpg
Percentage of detected human faces in human sample 96.0
Percentage of detected human faces in dog sample 12.0

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: I think it's reasonable requirement - otherwise there's not much to work with. It is also interesting to note that if the dog faces camera directly OpenCV is far more likely to detect human face in the picture.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [7]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [8]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [9]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [10]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [11]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer: Dog was detected in all of the dog samples - which means 100% success rate. And on top of that dog was detected in few human pictures as well - which is usually around 1% depending on the random seed.

In [12]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
d_f = 0
h_f = 0
for img_path in dog_files_short:
    if dog_detector(img_path):
        d_f += 1
    else:
        print(img_path)
        
for img_path in human_files_short:
    if dog_detector(img_path):
        print(img_path)
        h_f += 1
        
print("Dog detected in: {}% of dog samples".format(str((d_f/100.)*100.)))
print("Dog detected in: {}% of human samples".format(str((h_f/100.)*100.)))
lfw/Julio_Cesar_Chavez/Julio_Cesar_Chavez_0001.jpg
Dog detected in: 100.0% of dog samples
Dog detected in: 1.0% of human samples

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [13]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
100%|██████████| 6680/6680 [00:36<00:00, 183.66it/s]
100%|██████████| 836/836 [00:03<00:00, 209.04it/s]
100%|██████████| 835/835 [00:05<00:00, 152.97it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: I was testing many possible layouts. I found that using multiple Conv2D layers in row without scaling image size returned better results. Then after each such block I am scaling image and search smaller sections of image.

One block consists of 2xConv2D layers and MaxPooling2D layer. Blocks are connected with Activation and Dropout 0.25 layers. With other blocks. First block has resolution 222x222 pixels last block has resolution 49x49 pixels.

This structure ends with two fully connected layers with Dropout in between.

In [14]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense, Activation
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential

input_shape = (224, 224, 3)
num_classes = 133

mult_layers = 3
n_layers = 2
MIN_NEURONS = 20
MAX_NEURONS = 120
KERNEL = (3, 3)

# Determine the # of neurons in each convolutional layer
steps = np.floor(MAX_NEURONS / (n_layers + 1))
neurons = np.arange(MIN_NEURONS, MAX_NEURONS, steps)
neurons = neurons.astype(np.int32)

# Define a model
model = Sequential()

for i in range(0, mult_layers):
    # Add convolutional layers
    for i in range(0, n_layers):
        if i == 0:
            model.add(Conv2D(neurons[i], KERNEL, input_shape=input_shape))
        else:
            model.add(Conv2D(neurons[i], KERNEL))
    model.add(Activation('relu'))
    model.add(Dropout(0.25))
    # Add max pooling layer
    model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(MAX_NEURONS))
model.add(Activation('relu'))

model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Activation('sigmoid'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 222, 222, 20)      560       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 220, 220, 60)      10860     
_________________________________________________________________
activation_50 (Activation)   (None, 220, 220, 60)      0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 220, 220, 60)      0         
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 110, 110, 60)      0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 108, 108, 20)      10820     
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 106, 106, 60)      10860     
_________________________________________________________________
activation_51 (Activation)   (None, 106, 106, 60)      0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 106, 106, 60)      0         
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 53, 53, 60)        0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 51, 51, 20)        10820     
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 49, 49, 60)        10860     
_________________________________________________________________
activation_52 (Activation)   (None, 49, 49, 60)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 49, 49, 60)        0         
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 24, 24, 60)        0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 34560)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 120)               4147320   
_________________________________________________________________
activation_53 (Activation)   (None, 120)               0         
_________________________________________________________________
dropout_4 (Dropout)          (None, 120)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               16093     
_________________________________________________________________
activation_54 (Activation)   (None, 133)               0         
=================================================================
Total params: 4,218,193
Trainable params: 4,218,193
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [15]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
# model.summary()

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [19]:
from keras.callbacks import ModelCheckpoint

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 20

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 49s 7ms/step - loss: 4.9219 - acc: 0.0081 - val_loss: 4.8850 - val_acc: 0.0108

Epoch 00001: val_loss improved from inf to 4.88499, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 2/20
6680/6680 [==============================] - 47s 7ms/step - loss: 4.9151 - acc: 0.0090 - val_loss: 4.8797 - val_acc: 0.0108

Epoch 00002: val_loss improved from 4.88499 to 4.87970, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 3/20
6680/6680 [==============================] - 47s 7ms/step - loss: 4.8909 - acc: 0.0093 - val_loss: 4.8723 - val_acc: 0.0108

Epoch 00003: val_loss improved from 4.87970 to 4.87231, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 4/20
6680/6680 [==============================] - 47s 7ms/step - loss: 4.8905 - acc: 0.0115 - val_loss: 4.8639 - val_acc: 0.0144

Epoch 00004: val_loss improved from 4.87231 to 4.86390, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 5/20
6680/6680 [==============================] - 47s 7ms/step - loss: 4.8492 - acc: 0.0168 - val_loss: 4.8429 - val_acc: 0.0168

Epoch 00005: val_loss improved from 4.86390 to 4.84295, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 6/20
6680/6680 [==============================] - 47s 7ms/step - loss: 4.7818 - acc: 0.0198 - val_loss: 4.8328 - val_acc: 0.0275

Epoch 00006: val_loss improved from 4.84295 to 4.83280, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 7/20
6680/6680 [==============================] - 47s 7ms/step - loss: 4.6503 - acc: 0.0337 - val_loss: 4.7877 - val_acc: 0.0287

Epoch 00007: val_loss improved from 4.83280 to 4.78766, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 8/20
6680/6680 [==============================] - 47s 7ms/step - loss: 4.4191 - acc: 0.0602 - val_loss: 4.7577 - val_acc: 0.0263

Epoch 00008: val_loss improved from 4.78766 to 4.75770, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 9/20
6680/6680 [==============================] - 47s 7ms/step - loss: 4.1300 - acc: 0.0964 - val_loss: 4.7137 - val_acc: 0.0311

Epoch 00009: val_loss improved from 4.75770 to 4.71369, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 10/20
6680/6680 [==============================] - 47s 7ms/step - loss: 3.8864 - acc: 0.1361 - val_loss: 4.8497 - val_acc: 0.0240

Epoch 00010: val_loss did not improve from 4.71369
Epoch 11/20
6680/6680 [==============================] - 47s 7ms/step - loss: 3.6076 - acc: 0.1740 - val_loss: 4.7553 - val_acc: 0.0287

Epoch 00011: val_loss did not improve from 4.71369
Epoch 12/20
6680/6680 [==============================] - 47s 7ms/step - loss: 3.3147 - acc: 0.2184 - val_loss: 4.7549 - val_acc: 0.0216

Epoch 00012: val_loss did not improve from 4.71369
Epoch 13/20
6680/6680 [==============================] - 47s 7ms/step - loss: 2.1036 - acc: 0.1760 - val_loss: 1.1921e-07 - val_acc: 0.0096

Epoch 00013: val_loss improved from 4.71369 to 0.00000, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 14/20
6680/6680 [==============================] - 47s 7ms/step - loss: 1.1921e-07 - acc: 0.0096 - val_loss: 1.1921e-07 - val_acc: 0.0096

Epoch 00014: val_loss did not improve from 0.00000
Epoch 15/20
6680/6680 [==============================] - 47s 7ms/step - loss: 1.1921e-07 - acc: 0.0096 - val_loss: 1.1921e-07 - val_acc: 0.0096

Epoch 00015: val_loss did not improve from 0.00000
Epoch 16/20
6680/6680 [==============================] - 47s 7ms/step - loss: 1.1921e-07 - acc: 0.0096 - val_loss: 1.1921e-07 - val_acc: 0.0096

Epoch 00016: val_loss did not improve from 0.00000
Epoch 17/20
6680/6680 [==============================] - 47s 7ms/step - loss: 1.1921e-07 - acc: 0.0096 - val_loss: 1.1921e-07 - val_acc: 0.0096

Epoch 00017: val_loss did not improve from 0.00000
Epoch 18/20
6680/6680 [==============================] - 47s 7ms/step - loss: 1.1921e-07 - acc: 0.0096 - val_loss: 1.1921e-07 - val_acc: 0.0096

Epoch 00018: val_loss did not improve from 0.00000
Epoch 19/20
6680/6680 [==============================] - 47s 7ms/step - loss: 1.1921e-07 - acc: 0.0096 - val_loss: 1.1921e-07 - val_acc: 0.0096

Epoch 00019: val_loss did not improve from 0.00000
Epoch 20/20
6680/6680 [==============================] - 47s 7ms/step - loss: 1.1921e-07 - acc: 0.0096 - val_loss: 1.1921e-07 - val_acc: 0.0096

Epoch 00020: val_loss did not improve from 0.00000
Out[19]:
<keras.callbacks.History at 0x7fcbd778eda0>

Load the Model with the Best Validation Loss

In [20]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [21]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 0.9569%
In [22]:
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 222, 222, 20)      560       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 220, 220, 60)      10860     
_________________________________________________________________
activation_50 (Activation)   (None, 220, 220, 60)      0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 220, 220, 60)      0         
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 110, 110, 60)      0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 108, 108, 20)      10820     
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 106, 106, 60)      10860     
_________________________________________________________________
activation_51 (Activation)   (None, 106, 106, 60)      0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 106, 106, 60)      0         
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 53, 53, 60)        0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 51, 51, 20)        10820     
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 49, 49, 60)        10860     
_________________________________________________________________
activation_52 (Activation)   (None, 49, 49, 60)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 49, 49, 60)        0         
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 24, 24, 60)        0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 34560)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 120)               4147320   
_________________________________________________________________
activation_53 (Activation)   (None, 120)               0         
_________________________________________________________________
dropout_4 (Dropout)          (None, 120)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               16093     
_________________________________________________________________
activation_54 (Activation)   (None, 133)               0         
=================================================================
Total params: 4,218,193
Trainable params: 4,218,193
Non-trainable params: 0
_________________________________________________________________

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [23]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [24]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 512)               0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [25]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [26]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 1s 185us/step - loss: 11.6174 - acc: 0.1424 - val_loss: 9.7646 - val_acc: 0.2683

Epoch 00001: val_loss improved from inf to 9.76464, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 2/20
6680/6680 [==============================] - 1s 100us/step - loss: 8.8863 - acc: 0.3340 - val_loss: 8.8545 - val_acc: 0.3353

Epoch 00002: val_loss improved from 9.76464 to 8.85451, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 3/20
6680/6680 [==============================] - 2s 289us/step - loss: 8.3047 - acc: 0.4070 - val_loss: 8.5652 - val_acc: 0.3653

Epoch 00003: val_loss improved from 8.85451 to 8.56518, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 4/20
6680/6680 [==============================] - 2s 288us/step - loss: 7.9423 - acc: 0.4507 - val_loss: 8.4325 - val_acc: 0.3772

Epoch 00004: val_loss improved from 8.56518 to 8.43247, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 5/20
6680/6680 [==============================] - 2s 278us/step - loss: 7.6589 - acc: 0.4787 - val_loss: 8.2461 - val_acc: 0.4012

Epoch 00005: val_loss improved from 8.43247 to 8.24605, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 6/20
6680/6680 [==============================] - 1s 211us/step - loss: 7.4748 - acc: 0.4997 - val_loss: 8.1382 - val_acc: 0.3952

Epoch 00006: val_loss improved from 8.24605 to 8.13821, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 7/20
6680/6680 [==============================] - 1s 210us/step - loss: 7.2819 - acc: 0.5169 - val_loss: 7.9652 - val_acc: 0.4096

Epoch 00007: val_loss improved from 8.13821 to 7.96518, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 8/20
6680/6680 [==============================] - 1s 212us/step - loss: 7.0905 - acc: 0.5310 - val_loss: 7.7706 - val_acc: 0.4359

Epoch 00008: val_loss improved from 7.96518 to 7.77059, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 9/20
6680/6680 [==============================] - 1s 217us/step - loss: 7.0219 - acc: 0.5419 - val_loss: 7.7551 - val_acc: 0.4347

Epoch 00009: val_loss improved from 7.77059 to 7.75506, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 10/20
6680/6680 [==============================] - 1s 199us/step - loss: 6.9332 - acc: 0.5500 - val_loss: 7.6308 - val_acc: 0.4443

Epoch 00010: val_loss improved from 7.75506 to 7.63080, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 11/20
6680/6680 [==============================] - 1s 199us/step - loss: 6.7720 - acc: 0.5596 - val_loss: 7.6370 - val_acc: 0.4383

Epoch 00011: val_loss did not improve from 7.63080
Epoch 12/20
6680/6680 [==============================] - 1s 198us/step - loss: 6.6268 - acc: 0.5684 - val_loss: 7.4124 - val_acc: 0.4515

Epoch 00012: val_loss improved from 7.63080 to 7.41244, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 13/20
6680/6680 [==============================] - 1s 197us/step - loss: 6.5319 - acc: 0.5807 - val_loss: 7.4066 - val_acc: 0.4491

Epoch 00013: val_loss improved from 7.41244 to 7.40662, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 14/20
6680/6680 [==============================] - 1s 199us/step - loss: 6.4555 - acc: 0.5832 - val_loss: 7.3183 - val_acc: 0.4599

Epoch 00014: val_loss improved from 7.40662 to 7.31825, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 15/20
6680/6680 [==============================] - 2s 243us/step - loss: 6.3531 - acc: 0.5948 - val_loss: 7.2405 - val_acc: 0.4635

Epoch 00015: val_loss improved from 7.31825 to 7.24052, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 16/20
6680/6680 [==============================] - 2s 244us/step - loss: 6.2785 - acc: 0.5979 - val_loss: 7.2351 - val_acc: 0.4731

Epoch 00016: val_loss improved from 7.24052 to 7.23506, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 17/20
6680/6680 [==============================] - 2s 243us/step - loss: 6.1991 - acc: 0.6060 - val_loss: 7.1105 - val_acc: 0.4790

Epoch 00017: val_loss improved from 7.23506 to 7.11050, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 18/20
6680/6680 [==============================] - 2s 242us/step - loss: 6.1157 - acc: 0.6087 - val_loss: 6.9546 - val_acc: 0.4862

Epoch 00018: val_loss improved from 7.11050 to 6.95465, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 19/20
6680/6680 [==============================] - 1s 146us/step - loss: 6.0163 - acc: 0.6156 - val_loss: 6.9843 - val_acc: 0.4886

Epoch 00019: val_loss did not improve from 6.95465
Epoch 20/20
6680/6680 [==============================] - 1s 197us/step - loss: 5.8464 - acc: 0.6238 - val_loss: 6.8691 - val_acc: 0.4886

Epoch 00020: val_loss improved from 6.95465 to 6.86914, saving model to saved_models/weights.best.VGG16.hdf5
Out[26]:
<keras.callbacks.History at 0x7fcbd6845128>

Load the Model with the Best Validation Loss

In [27]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [28]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 49.1627%

Predict Dog Breed with the Model

In [29]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [30]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']
valid_Xception = bottleneck_features['valid']
test_Xception = bottleneck_features['test']
In [31]:
Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
# Xception_model.add(Dense(250, activation='relu'))
# Xception_model.add(Dropout(0.25))
# Xception_model.add(Activation('relu'))
# Xception_model.add(Dropout(0.5))
Xception_model.add(Dense(133, activation='softmax'))

Xception_model.summary()

Xception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
                               verbose=1, save_best_only=True)

Xception_model.fit(train_Xception, train_targets, 
          validation_data=(valid_Xception, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_4 ( (None, 2048)              0         
_________________________________________________________________
dense_6 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 3s 400us/step - loss: 1.0375 - acc: 0.7409 - val_loss: 0.5228 - val_acc: 0.8251

Epoch 00001: val_loss improved from inf to 0.52285, saving model to saved_models/weights.best.Xception.hdf5
Epoch 2/20
6680/6680 [==============================] - 2s 277us/step - loss: 0.3988 - acc: 0.8747 - val_loss: 0.4843 - val_acc: 0.8383

Epoch 00002: val_loss improved from 0.52285 to 0.48430, saving model to saved_models/weights.best.Xception.hdf5
Epoch 3/20
6680/6680 [==============================] - 2s 343us/step - loss: 0.3234 - acc: 0.8975 - val_loss: 0.4594 - val_acc: 0.8551

Epoch 00003: val_loss improved from 0.48430 to 0.45937, saving model to saved_models/weights.best.Xception.hdf5
Epoch 4/20
6680/6680 [==============================] - 2s 349us/step - loss: 0.2772 - acc: 0.9139 - val_loss: 0.5037 - val_acc: 0.8467

Epoch 00004: val_loss did not improve from 0.45937
Epoch 5/20
6680/6680 [==============================] - 2s 358us/step - loss: 0.2445 - acc: 0.9234 - val_loss: 0.5080 - val_acc: 0.8527

Epoch 00005: val_loss did not improve from 0.45937
Epoch 6/20
6680/6680 [==============================] - 2s 334us/step - loss: 0.2202 - acc: 0.9335 - val_loss: 0.4969 - val_acc: 0.8647

Epoch 00006: val_loss did not improve from 0.45937
Epoch 7/20
6680/6680 [==============================] - 2s 326us/step - loss: 0.2007 - acc: 0.9389 - val_loss: 0.5358 - val_acc: 0.8575

Epoch 00007: val_loss did not improve from 0.45937
Epoch 8/20
6680/6680 [==============================] - 2s 371us/step - loss: 0.1825 - acc: 0.9461 - val_loss: 0.5751 - val_acc: 0.8467

Epoch 00008: val_loss did not improve from 0.45937
Epoch 9/20
6680/6680 [==============================] - 3s 384us/step - loss: 0.1660 - acc: 0.9475 - val_loss: 0.5536 - val_acc: 0.8563

Epoch 00009: val_loss did not improve from 0.45937
Epoch 10/20
6680/6680 [==============================] - 2s 351us/step - loss: 0.1466 - acc: 0.9536 - val_loss: 0.5385 - val_acc: 0.8587

Epoch 00010: val_loss did not improve from 0.45937
Epoch 11/20
6680/6680 [==============================] - 3s 405us/step - loss: 0.1375 - acc: 0.9576 - val_loss: 0.5708 - val_acc: 0.8503

Epoch 00011: val_loss did not improve from 0.45937
Epoch 12/20
6680/6680 [==============================] - 3s 378us/step - loss: 0.1252 - acc: 0.9623 - val_loss: 0.5930 - val_acc: 0.8635

Epoch 00012: val_loss did not improve from 0.45937
Epoch 13/20
6680/6680 [==============================] - 2s 369us/step - loss: 0.1160 - acc: 0.9644 - val_loss: 0.5867 - val_acc: 0.8635

Epoch 00013: val_loss did not improve from 0.45937
Epoch 14/20
6680/6680 [==============================] - 2s 313us/step - loss: 0.1079 - acc: 0.9678 - val_loss: 0.6074 - val_acc: 0.8575

Epoch 00014: val_loss did not improve from 0.45937
Epoch 15/20
6680/6680 [==============================] - 3s 390us/step - loss: 0.1026 - acc: 0.9695 - val_loss: 0.6233 - val_acc: 0.8599

Epoch 00015: val_loss did not improve from 0.45937
Epoch 16/20
6680/6680 [==============================] - 3s 375us/step - loss: 0.0915 - acc: 0.9734 - val_loss: 0.6268 - val_acc: 0.8635

Epoch 00016: val_loss did not improve from 0.45937
Epoch 17/20
6680/6680 [==============================] - 3s 386us/step - loss: 0.0874 - acc: 0.9754 - val_loss: 0.6423 - val_acc: 0.8551

Epoch 00017: val_loss did not improve from 0.45937
Epoch 18/20
6680/6680 [==============================] - 2s 326us/step - loss: 0.0803 - acc: 0.9760 - val_loss: 0.6479 - val_acc: 0.8563

Epoch 00018: val_loss did not improve from 0.45937
Epoch 19/20
6680/6680 [==============================] - 2s 326us/step - loss: 0.0764 - acc: 0.9780 - val_loss: 0.6696 - val_acc: 0.8587

Epoch 00019: val_loss did not improve from 0.45937
Epoch 20/20
6680/6680 [==============================] - 3s 380us/step - loss: 0.0726 - acc: 0.9811 - val_loss: 0.6743 - val_acc: 0.8623

Epoch 00020: val_loss did not improve from 0.45937
Out[31]:
<keras.callbacks.History at 0x7fcbd65649e8>
In [32]:
Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')

# get index of predicted dog breed for each image in test set
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 84.3301%
In [34]:
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

datagen_train = ImageDataGenerator(
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True)

datagen_valid = ImageDataGenerator(
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True)

# fit augmented image generator on data
datagen_train.fit(train_Xception)
datagen_valid.fit(valid_Xception)

checkpointer = ModelCheckpoint(filepath='saved_models/aug_Xception.weights.best.hdf5', verbose=1, 
                               save_best_only=True)

aug_Xception_model = Sequential()
aug_Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
aug_Xception_model.add(Dense(133, activation='softmax'))

aug_Xception_model.summary()

aug_Xception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

aug_Xception_model.fit_generator(datagen_train.flow(train_Xception, train_targets, batch_size=batch_size),
                                 steps_per_epoch=train_Xception.shape[0] // batch_size,
                                 epochs=5, verbose=2, callbacks=[checkpointer],
                                 validation_data=datagen_valid.flow(valid_Xception, valid_targets, batch_size=batch_size),
                                 validation_steps=valid_Xception.shape[0] // batch_size)
/home/martin/anaconda3/envs/dog/lib/python3.6/site-packages/keras_preprocessing/image.py:1213: UserWarning: Expected input to be images (as Numpy array) following the data format convention "channels_last" (channels on axis 3), i.e. expected either 1, 3 or 4 channels on axis 3. However, it was passed an array with shape (6680, 7, 7, 2048) (2048 channels).
  ' channels).')
/home/martin/anaconda3/envs/dog/lib/python3.6/site-packages/keras_preprocessing/image.py:1213: UserWarning: Expected input to be images (as Numpy array) following the data format convention "channels_last" (channels on axis 3), i.e. expected either 1, 3 or 4 channels on axis 3. However, it was passed an array with shape (835, 7, 7, 2048) (2048 channels).
  ' channels).')
/home/martin/anaconda3/envs/dog/lib/python3.6/site-packages/keras_preprocessing/image.py:1437: UserWarning: NumpyArrayIterator is set to use the data format convention "channels_last" (channels on axis 3), i.e. expected either 1, 3, or 4 channels on axis 3. However, it was passed an array with shape (6680, 7, 7, 2048) (2048 channels).
  str(self.x.shape[channels_axis]) + ' channels).')
/home/martin/anaconda3/envs/dog/lib/python3.6/site-packages/keras_preprocessing/image.py:1437: UserWarning: NumpyArrayIterator is set to use the data format convention "channels_last" (channels on axis 3), i.e. expected either 1, 3, or 4 channels on axis 3. However, it was passed an array with shape (835, 7, 7, 2048) (2048 channels).
  str(self.x.shape[channels_axis]) + ' channels).')
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_6 ( (None, 2048)              0         
_________________________________________________________________
dense_8 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
 - 202s - loss: 1.0617 - acc: 0.7323 - val_loss: 0.5098 - val_acc: 0.8335

Epoch 00001: val_loss improved from inf to 0.50978, saving model to saved_models/aug_Xception.weights.best.hdf5
Epoch 2/5
 - 197s - loss: 0.4068 - acc: 0.8705 - val_loss: 0.5017 - val_acc: 0.8455

Epoch 00002: val_loss improved from 0.50978 to 0.50169, saving model to saved_models/aug_Xception.weights.best.hdf5
Epoch 3/5
 - 195s - loss: 0.3308 - acc: 0.8955 - val_loss: 0.4788 - val_acc: 0.8467

Epoch 00003: val_loss improved from 0.50169 to 0.47877, saving model to saved_models/aug_Xception.weights.best.hdf5
Epoch 4/5
 - 196s - loss: 0.2800 - acc: 0.9162 - val_loss: 0.5214 - val_acc: 0.8419

Epoch 00004: val_loss did not improve from 0.47877
Epoch 5/5
 - 196s - loss: 0.2461 - acc: 0.9246 - val_loss: 0.5205 - val_acc: 0.8395

Epoch 00005: val_loss did not improve from 0.47877
Out[34]:
<keras.callbacks.History at 0x7fcbd611d7b8>
In [35]:
aug_Xception_model.load_weights('saved_models/aug_Xception.weights.best.hdf5')

# get index of predicted dog breed for each image in test set
aug_Xception_predictions = [np.argmax(aug_Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(aug_Xception_predictions)==np.argmax(test_targets, axis=1))/len(aug_Xception_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 84.4498%
In [36]:
bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
train_Resnet50 = bottleneck_features['train']
valid_Resnet50 = bottleneck_features['valid']
test_Resnet50 = bottleneck_features['test']

Resnet50_model = Sequential()
Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
# Resnet50_model.add(Dense(500))
# Resnet50_model.add(Activation('relu'))
# Resnet50_model.add(Dropout(0.5))
Resnet50_model.add(Dense(133, activation='softmax'))

Resnet50_model.summary()

Resnet50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5', 
                               verbose=1, save_best_only=True)

Resnet50_model.fit(train_Resnet50, train_targets, 
          validation_data=(valid_Resnet50, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_7 ( (None, 2048)              0         
_________________________________________________________________
dense_9 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 1s 145us/step - loss: 1.6270 - acc: 0.6001 - val_loss: 0.7770 - val_acc: 0.7557

Epoch 00001: val_loss improved from inf to 0.77705, saving model to saved_models/weights.best.Resnet50.hdf5
Epoch 2/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.4382 - acc: 0.8657 - val_loss: 0.6658 - val_acc: 0.7916

Epoch 00002: val_loss improved from 0.77705 to 0.66583, saving model to saved_models/weights.best.Resnet50.hdf5
Epoch 3/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.2599 - acc: 0.9189 - val_loss: 0.6844 - val_acc: 0.7964

Epoch 00003: val_loss did not improve from 0.66583
Epoch 4/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.1730 - acc: 0.9446 - val_loss: 0.6564 - val_acc: 0.8060

Epoch 00004: val_loss improved from 0.66583 to 0.65643, saving model to saved_models/weights.best.Resnet50.hdf5
Epoch 5/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.1210 - acc: 0.9647 - val_loss: 0.6982 - val_acc: 0.8120

Epoch 00005: val_loss did not improve from 0.65643
Epoch 6/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0867 - acc: 0.9723 - val_loss: 0.6132 - val_acc: 0.8228

Epoch 00006: val_loss improved from 0.65643 to 0.61317, saving model to saved_models/weights.best.Resnet50.hdf5
Epoch 7/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0611 - acc: 0.9801 - val_loss: 0.6719 - val_acc: 0.8347

Epoch 00007: val_loss did not improve from 0.61317
Epoch 8/20
6680/6680 [==============================] - 0s 70us/step - loss: 0.0497 - acc: 0.9858 - val_loss: 0.7148 - val_acc: 0.8168

Epoch 00008: val_loss did not improve from 0.61317
Epoch 9/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0340 - acc: 0.9898 - val_loss: 0.7059 - val_acc: 0.8240

Epoch 00009: val_loss did not improve from 0.61317
Epoch 10/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0277 - acc: 0.9930 - val_loss: 0.7416 - val_acc: 0.8156

Epoch 00010: val_loss did not improve from 0.61317
Epoch 11/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0216 - acc: 0.9946 - val_loss: 0.7534 - val_acc: 0.8120

Epoch 00011: val_loss did not improve from 0.61317
Epoch 12/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0164 - acc: 0.9957 - val_loss: 0.7403 - val_acc: 0.8251

Epoch 00012: val_loss did not improve from 0.61317
Epoch 13/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0152 - acc: 0.9966 - val_loss: 0.7633 - val_acc: 0.8359

Epoch 00013: val_loss did not improve from 0.61317
Epoch 14/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0107 - acc: 0.9975 - val_loss: 0.7694 - val_acc: 0.8204

Epoch 00014: val_loss did not improve from 0.61317
Epoch 15/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0086 - acc: 0.9978 - val_loss: 0.8406 - val_acc: 0.8311

Epoch 00015: val_loss did not improve from 0.61317
Epoch 16/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0098 - acc: 0.9981 - val_loss: 0.8344 - val_acc: 0.8204

Epoch 00016: val_loss did not improve from 0.61317
Epoch 17/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0079 - acc: 0.9981 - val_loss: 0.8378 - val_acc: 0.8240

Epoch 00017: val_loss did not improve from 0.61317
Epoch 18/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0073 - acc: 0.9978 - val_loss: 0.8612 - val_acc: 0.8084

Epoch 00018: val_loss did not improve from 0.61317
Epoch 19/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0063 - acc: 0.9987 - val_loss: 0.8836 - val_acc: 0.8275

Epoch 00019: val_loss did not improve from 0.61317
Epoch 20/20
6680/6680 [==============================] - 0s 69us/step - loss: 0.0055 - acc: 0.9985 - val_loss: 0.8888 - val_acc: 0.8240

Epoch 00020: val_loss did not improve from 0.61317
Out[36]:
<keras.callbacks.History at 0x7fcbd65df320>
In [37]:
Resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')

# get index of predicted dog breed for each image in test set
Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Resnet50]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 81.5789%
In [38]:
bottleneck_features = np.load('bottleneck_features/DogInceptionV3Data.npz')
train_InceptionV3 = bottleneck_features['train']
valid_InceptionV3 = bottleneck_features['valid']
test_InceptionV3 = bottleneck_features['test']

InceptionV3_model = Sequential()
InceptionV3_model.add(GlobalAveragePooling2D(input_shape=train_InceptionV3.shape[1:]))
InceptionV3_model.add(Dropout(0.25))
InceptionV3_model.add(Dense(500))
InceptionV3_model.add(Activation('relu'))
InceptionV3_model.add(Dropout(0.5))
InceptionV3_model.add(Dense(133, activation='softmax'))

InceptionV3_model.summary()

InceptionV3_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.InceptionV3.hdf5', 
                               verbose=1, save_best_only=True)

InceptionV3_model.fit(train_InceptionV3, train_targets, 
          validation_data=(valid_InceptionV3, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_8 ( (None, 2048)              0         
_________________________________________________________________
dropout_5 (Dropout)          (None, 2048)              0         
_________________________________________________________________
dense_10 (Dense)             (None, 500)               1024500   
_________________________________________________________________
activation_55 (Activation)   (None, 500)               0         
_________________________________________________________________
dropout_6 (Dropout)          (None, 500)               0         
_________________________________________________________________
dense_11 (Dense)             (None, 133)               66633     
=================================================================
Total params: 1,091,133
Trainable params: 1,091,133
Non-trainable params: 0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 3s 449us/step - loss: 2.0944 - acc: 0.5284 - val_loss: 0.6820 - val_acc: 0.7772

Epoch 00001: val_loss improved from inf to 0.68204, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 2/20
6680/6680 [==============================] - 2s 332us/step - loss: 1.0487 - acc: 0.7190 - val_loss: 0.6563 - val_acc: 0.8012

Epoch 00002: val_loss improved from 0.68204 to 0.65629, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 3/20
6680/6680 [==============================] - 3s 422us/step - loss: 0.8779 - acc: 0.7695 - val_loss: 0.6256 - val_acc: 0.8168

Epoch 00003: val_loss improved from 0.65629 to 0.62559, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 4/20
6680/6680 [==============================] - 3s 378us/step - loss: 0.8191 - acc: 0.7873 - val_loss: 0.6066 - val_acc: 0.8359

Epoch 00004: val_loss improved from 0.62559 to 0.60659, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 5/20
6680/6680 [==============================] - 3s 421us/step - loss: 0.7548 - acc: 0.7979 - val_loss: 0.6304 - val_acc: 0.8323

Epoch 00005: val_loss did not improve from 0.60659
Epoch 6/20
6680/6680 [==============================] - 3s 420us/step - loss: 0.7114 - acc: 0.8202 - val_loss: 0.6679 - val_acc: 0.8323

Epoch 00006: val_loss did not improve from 0.60659
Epoch 7/20
6680/6680 [==============================] - 3s 422us/step - loss: 0.6893 - acc: 0.8277 - val_loss: 0.6639 - val_acc: 0.8515

Epoch 00007: val_loss did not improve from 0.60659
Epoch 8/20
6680/6680 [==============================] - 3s 420us/step - loss: 0.6519 - acc: 0.8377 - val_loss: 0.7446 - val_acc: 0.8383

Epoch 00008: val_loss did not improve from 0.60659
Epoch 9/20
6680/6680 [==============================] - 3s 420us/step - loss: 0.6277 - acc: 0.8425 - val_loss: 0.7933 - val_acc: 0.8383

Epoch 00009: val_loss did not improve from 0.60659
Epoch 10/20
6680/6680 [==============================] - 3s 404us/step - loss: 0.6246 - acc: 0.8475 - val_loss: 0.7990 - val_acc: 0.8479

Epoch 00010: val_loss did not improve from 0.60659
Epoch 11/20
6680/6680 [==============================] - 3s 398us/step - loss: 0.6293 - acc: 0.8472 - val_loss: 0.8048 - val_acc: 0.8347

Epoch 00011: val_loss did not improve from 0.60659
Epoch 12/20
6680/6680 [==============================] - 3s 422us/step - loss: 0.5846 - acc: 0.8569 - val_loss: 0.7911 - val_acc: 0.8347

Epoch 00012: val_loss did not improve from 0.60659
Epoch 13/20
6680/6680 [==============================] - 3s 420us/step - loss: 0.5783 - acc: 0.8614 - val_loss: 0.8420 - val_acc: 0.8551

Epoch 00013: val_loss did not improve from 0.60659
Epoch 14/20
6680/6680 [==============================] - 3s 420us/step - loss: 0.5924 - acc: 0.8611 - val_loss: 0.8002 - val_acc: 0.8443

Epoch 00014: val_loss did not improve from 0.60659
Epoch 15/20
6680/6680 [==============================] - 3s 419us/step - loss: 0.5291 - acc: 0.8749 - val_loss: 0.9255 - val_acc: 0.8539

Epoch 00015: val_loss did not improve from 0.60659
Epoch 16/20
6680/6680 [==============================] - 3s 420us/step - loss: 0.5527 - acc: 0.8737 - val_loss: 0.9105 - val_acc: 0.8503

Epoch 00016: val_loss did not improve from 0.60659
Epoch 17/20
6680/6680 [==============================] - 3s 420us/step - loss: 0.5116 - acc: 0.8804 - val_loss: 0.8160 - val_acc: 0.8407

Epoch 00017: val_loss did not improve from 0.60659
Epoch 18/20
6680/6680 [==============================] - 3s 421us/step - loss: 0.5245 - acc: 0.8801 - val_loss: 0.8816 - val_acc: 0.8419

Epoch 00018: val_loss did not improve from 0.60659
Epoch 19/20
6680/6680 [==============================] - 3s 420us/step - loss: 0.5165 - acc: 0.8837 - val_loss: 0.8540 - val_acc: 0.8491

Epoch 00019: val_loss did not improve from 0.60659
Epoch 20/20
6680/6680 [==============================] - 3s 418us/step - loss: 0.4872 - acc: 0.8882 - val_loss: 0.9264 - val_acc: 0.8623

Epoch 00020: val_loss did not improve from 0.60659
Out[38]:
<keras.callbacks.History at 0x7fcbd6966cf8>
In [39]:
InceptionV3_model.load_weights('saved_models/weights.best.InceptionV3.hdf5')

# get index of predicted dog breed for each image in test set
InceptionV3_predictions = [np.argmax(InceptionV3_model.predict(np.expand_dims(feature, axis=0))) for feature in test_InceptionV3]

# report test accuracy
test_accuracy = 100*np.sum(np.array(InceptionV3_predictions)==np.argmax(test_targets, axis=1))/len(InceptionV3_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 78.9474%
In [40]:
bottleneck_features = np.load('bottleneck_features/DogVGG19Data.npz')
train_VGG19 = bottleneck_features['train']
valid_VGG19 = bottleneck_features['valid']
test_VGG19 = bottleneck_features['test']

VGG19_model = Sequential()
VGG19_model.add(GlobalAveragePooling2D(input_shape=train_VGG19.shape[1:]))
# VGG19_model.add(Dropout(0.25))
# VGG19_model.add(Dense(500, activation='relu'))
# VGG19_model.add(Dropout(0.25))
VGG19_model.add(Dense(133, activation='softmax'))

VGG19_model.summary()

VGG19_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5', 
                               verbose=1, save_best_only=True)

VGG19_model.fit(train_VGG19, train_targets, 
          validation_data=(valid_VGG19, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_9 ( (None, 512)               0         
_________________________________________________________________
dense_12 (Dense)             (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 1s 183us/step - loss: 11.7228 - acc: 0.1415 - val_loss: 9.8939 - val_acc: 0.2623

Epoch 00001: val_loss improved from inf to 9.89386, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 2/20
6680/6680 [==============================] - 1s 103us/step - loss: 9.0860 - acc: 0.3214 - val_loss: 8.9971 - val_acc: 0.3353

Epoch 00002: val_loss improved from 9.89386 to 8.99707, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 3/20
6680/6680 [==============================] - 1s 200us/step - loss: 8.3334 - acc: 0.4024 - val_loss: 8.6420 - val_acc: 0.3713

Epoch 00003: val_loss improved from 8.99707 to 8.64205, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 4/20
6680/6680 [==============================] - 1s 199us/step - loss: 8.0819 - acc: 0.4415 - val_loss: 8.4027 - val_acc: 0.3880

Epoch 00004: val_loss improved from 8.64205 to 8.40272, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 5/20
6680/6680 [==============================] - 1s 201us/step - loss: 7.8668 - acc: 0.4696 - val_loss: 8.3195 - val_acc: 0.4072

Epoch 00005: val_loss improved from 8.40272 to 8.31946, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 6/20
6680/6680 [==============================] - 1s 201us/step - loss: 7.7275 - acc: 0.4856 - val_loss: 8.1696 - val_acc: 0.4096

Epoch 00006: val_loss improved from 8.31946 to 8.16964, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 7/20
6680/6680 [==============================] - 2s 247us/step - loss: 7.4024 - acc: 0.5055 - val_loss: 7.8108 - val_acc: 0.4503

Epoch 00007: val_loss improved from 8.16964 to 7.81078, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 8/20
6680/6680 [==============================] - 2s 246us/step - loss: 7.1890 - acc: 0.5250 - val_loss: 7.7987 - val_acc: 0.4359

Epoch 00008: val_loss improved from 7.81078 to 7.79874, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 9/20
6680/6680 [==============================] - 2s 246us/step - loss: 7.0530 - acc: 0.5388 - val_loss: 7.6914 - val_acc: 0.4371

Epoch 00009: val_loss improved from 7.79874 to 7.69137, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 10/20
6680/6680 [==============================] - 2s 247us/step - loss: 6.9709 - acc: 0.5488 - val_loss: 7.6711 - val_acc: 0.4503

Epoch 00010: val_loss improved from 7.69137 to 7.67111, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 11/20
6680/6680 [==============================] - 2s 292us/step - loss: 6.9007 - acc: 0.5561 - val_loss: 7.5577 - val_acc: 0.4563

Epoch 00011: val_loss improved from 7.67111 to 7.55771, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 12/20
6680/6680 [==============================] - 2s 292us/step - loss: 6.8632 - acc: 0.5636 - val_loss: 7.5294 - val_acc: 0.4623

Epoch 00012: val_loss improved from 7.55771 to 7.52937, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 13/20
6680/6680 [==============================] - 2s 291us/step - loss: 6.8012 - acc: 0.5654 - val_loss: 7.4352 - val_acc: 0.4575

Epoch 00013: val_loss improved from 7.52937 to 7.43519, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 14/20
6680/6680 [==============================] - 2s 292us/step - loss: 6.5936 - acc: 0.5735 - val_loss: 7.2836 - val_acc: 0.4683

Epoch 00014: val_loss improved from 7.43519 to 7.28358, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 15/20
6680/6680 [==============================] - 2s 227us/step - loss: 6.3693 - acc: 0.5912 - val_loss: 7.1918 - val_acc: 0.4707

Epoch 00015: val_loss improved from 7.28358 to 7.19175, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 16/20
6680/6680 [==============================] - 1s 194us/step - loss: 6.3181 - acc: 0.5978 - val_loss: 7.1103 - val_acc: 0.4910

Epoch 00016: val_loss improved from 7.19175 to 7.11029, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 17/20
6680/6680 [==============================] - 1s 170us/step - loss: 6.2059 - acc: 0.6037 - val_loss: 7.0183 - val_acc: 0.4922

Epoch 00017: val_loss improved from 7.11029 to 7.01830, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 18/20
6680/6680 [==============================] - 1s 170us/step - loss: 6.1652 - acc: 0.6105 - val_loss: 7.0376 - val_acc: 0.4982

Epoch 00018: val_loss did not improve from 7.01830
Epoch 19/20
6680/6680 [==============================] - 1s 200us/step - loss: 6.1517 - acc: 0.6145 - val_loss: 7.0428 - val_acc: 0.5018

Epoch 00019: val_loss did not improve from 7.01830
Epoch 20/20
6680/6680 [==============================] - 1s 200us/step - loss: 6.1438 - acc: 0.6157 - val_loss: 6.9883 - val_acc: 0.5066

Epoch 00020: val_loss improved from 7.01830 to 6.98831, saving model to saved_models/weights.best.VGG19.hdf5
Out[40]:
<keras.callbacks.History at 0x7fcbd7e4dcc0>
In [41]:
VGG19_model.load_weights('saved_models/weights.best.VGG19.hdf5')

# get index of predicted dog breed for each image in test set
VGG19_predictions = [np.argmax(VGG19_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG19]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG19_predictions)==np.argmax(test_targets, axis=1))/len(VGG19_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 49.2823%
In [42]:
aug_Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_6 ( (None, 2048)              0         
_________________________________________________________________
dense_8 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: I was thinking of using my model because it has best accuracy. But something is weird is going on. I will use Xception model. I trained Xception augmented model, but accuracy didn't improve significantly - based on the warning messages I am not sure that augmentation occurred. I suspect there might be problem with pre-trained data, it seems it might be transformed to the form not suitable for augmentation.

I tried multiple setups with Xception pre-trained model.

I tried 1-2 fully connected layers with different number of neurons between pre-trained models and output layer with different values for dropout. I found the best results with Xception (augmented) model. I will use this model.

In [19]:
### TODO: Define your architecture.
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from keras.applications.xception import Xception
from keras.models import Model


# 'saved_models/aug_Xception.weights.best.hdf5'
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.final_model.hdf5', verbose=1, 
                               save_best_only=True)

base_model = Xception(input_shape=input_shape, weights='imagenet', include_top=False)
# base_model = Xception(input_shape=input_shape, weights=None, include_top=False)

# Top Model Block
# x = GlobalAveragePooling2D()(base_model.output)
predictions = Dense(num_classes, activation='softmax')(GlobalAveragePooling2D()(base_model.output))

# add your top layer block to your base model
model = Model(base_model.input, predictions)

model.summary()

# aug_Xception_model.fit_generator(datagen_train.flow(train_Xception, train_targets, batch_size=batch_size),
#                                  steps_per_epoch=train_Xception.shape[0] // batch_size,
#                                  epochs=5, verbose=2, callbacks=[checkpointer],
#                                  validation_data=datagen_valid.flow(valid_Xception, valid_targets, batch_size=batch_size),
#                                  validation_steps=valid_Xception.shape[0] // batch_size)
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_3 (InputLayer)            (None, 224, 224, 3)  0                                            
__________________________________________________________________________________________________
block1_conv1 (Conv2D)           (None, 111, 111, 32) 864         input_3[0][0]                    
__________________________________________________________________________________________________
block1_conv1_bn (BatchNormaliza (None, 111, 111, 32) 128         block1_conv1[0][0]               
__________________________________________________________________________________________________
block1_conv1_act (Activation)   (None, 111, 111, 32) 0           block1_conv1_bn[0][0]            
__________________________________________________________________________________________________
block1_conv2 (Conv2D)           (None, 109, 109, 64) 18432       block1_conv1_act[0][0]           
__________________________________________________________________________________________________
block1_conv2_bn (BatchNormaliza (None, 109, 109, 64) 256         block1_conv2[0][0]               
__________________________________________________________________________________________________
block1_conv2_act (Activation)   (None, 109, 109, 64) 0           block1_conv2_bn[0][0]            
__________________________________________________________________________________________________
block2_sepconv1 (SeparableConv2 (None, 109, 109, 128 8768        block1_conv2_act[0][0]           
__________________________________________________________________________________________________
block2_sepconv1_bn (BatchNormal (None, 109, 109, 128 512         block2_sepconv1[0][0]            
__________________________________________________________________________________________________
block2_sepconv2_act (Activation (None, 109, 109, 128 0           block2_sepconv1_bn[0][0]         
__________________________________________________________________________________________________
block2_sepconv2 (SeparableConv2 (None, 109, 109, 128 17536       block2_sepconv2_act[0][0]        
__________________________________________________________________________________________________
block2_sepconv2_bn (BatchNormal (None, 109, 109, 128 512         block2_sepconv2[0][0]            
__________________________________________________________________________________________________
conv2d_11 (Conv2D)              (None, 55, 55, 128)  8192        block1_conv2_act[0][0]           
__________________________________________________________________________________________________
block2_pool (MaxPooling2D)      (None, 55, 55, 128)  0           block2_sepconv2_bn[0][0]         
__________________________________________________________________________________________________
batch_normalization_5 (BatchNor (None, 55, 55, 128)  512         conv2d_11[0][0]                  
__________________________________________________________________________________________________
add_29 (Add)                    (None, 55, 55, 128)  0           block2_pool[0][0]                
                                                                 batch_normalization_5[0][0]      
__________________________________________________________________________________________________
block3_sepconv1_act (Activation (None, 55, 55, 128)  0           add_29[0][0]                     
__________________________________________________________________________________________________
block3_sepconv1 (SeparableConv2 (None, 55, 55, 256)  33920       block3_sepconv1_act[0][0]        
__________________________________________________________________________________________________
block3_sepconv1_bn (BatchNormal (None, 55, 55, 256)  1024        block3_sepconv1[0][0]            
__________________________________________________________________________________________________
block3_sepconv2_act (Activation (None, 55, 55, 256)  0           block3_sepconv1_bn[0][0]         
__________________________________________________________________________________________________
block3_sepconv2 (SeparableConv2 (None, 55, 55, 256)  67840       block3_sepconv2_act[0][0]        
__________________________________________________________________________________________________
block3_sepconv2_bn (BatchNormal (None, 55, 55, 256)  1024        block3_sepconv2[0][0]            
__________________________________________________________________________________________________
conv2d_12 (Conv2D)              (None, 28, 28, 256)  32768       add_29[0][0]                     
__________________________________________________________________________________________________
block3_pool (MaxPooling2D)      (None, 28, 28, 256)  0           block3_sepconv2_bn[0][0]         
__________________________________________________________________________________________________
batch_normalization_6 (BatchNor (None, 28, 28, 256)  1024        conv2d_12[0][0]                  
__________________________________________________________________________________________________
add_30 (Add)                    (None, 28, 28, 256)  0           block3_pool[0][0]                
                                                                 batch_normalization_6[0][0]      
__________________________________________________________________________________________________
block4_sepconv1_act (Activation (None, 28, 28, 256)  0           add_30[0][0]                     
__________________________________________________________________________________________________
block4_sepconv1 (SeparableConv2 (None, 28, 28, 728)  188672      block4_sepconv1_act[0][0]        
__________________________________________________________________________________________________
block4_sepconv1_bn (BatchNormal (None, 28, 28, 728)  2912        block4_sepconv1[0][0]            
__________________________________________________________________________________________________
block4_sepconv2_act (Activation (None, 28, 28, 728)  0           block4_sepconv1_bn[0][0]         
__________________________________________________________________________________________________
block4_sepconv2 (SeparableConv2 (None, 28, 28, 728)  536536      block4_sepconv2_act[0][0]        
__________________________________________________________________________________________________
block4_sepconv2_bn (BatchNormal (None, 28, 28, 728)  2912        block4_sepconv2[0][0]            
__________________________________________________________________________________________________
conv2d_13 (Conv2D)              (None, 14, 14, 728)  186368      add_30[0][0]                     
__________________________________________________________________________________________________
block4_pool (MaxPooling2D)      (None, 14, 14, 728)  0           block4_sepconv2_bn[0][0]         
__________________________________________________________________________________________________
batch_normalization_7 (BatchNor (None, 14, 14, 728)  2912        conv2d_13[0][0]                  
__________________________________________________________________________________________________
add_31 (Add)                    (None, 14, 14, 728)  0           block4_pool[0][0]                
                                                                 batch_normalization_7[0][0]      
__________________________________________________________________________________________________
block5_sepconv1_act (Activation (None, 14, 14, 728)  0           add_31[0][0]                     
__________________________________________________________________________________________________
block5_sepconv1 (SeparableConv2 (None, 14, 14, 728)  536536      block5_sepconv1_act[0][0]        
__________________________________________________________________________________________________
block5_sepconv1_bn (BatchNormal (None, 14, 14, 728)  2912        block5_sepconv1[0][0]            
__________________________________________________________________________________________________
block5_sepconv2_act (Activation (None, 14, 14, 728)  0           block5_sepconv1_bn[0][0]         
__________________________________________________________________________________________________
block5_sepconv2 (SeparableConv2 (None, 14, 14, 728)  536536      block5_sepconv2_act[0][0]        
__________________________________________________________________________________________________
block5_sepconv2_bn (BatchNormal (None, 14, 14, 728)  2912        block5_sepconv2[0][0]            
__________________________________________________________________________________________________
block5_sepconv3_act (Activation (None, 14, 14, 728)  0           block5_sepconv2_bn[0][0]         
__________________________________________________________________________________________________
block5_sepconv3 (SeparableConv2 (None, 14, 14, 728)  536536      block5_sepconv3_act[0][0]        
__________________________________________________________________________________________________
block5_sepconv3_bn (BatchNormal (None, 14, 14, 728)  2912        block5_sepconv3[0][0]            
__________________________________________________________________________________________________
add_32 (Add)                    (None, 14, 14, 728)  0           block5_sepconv3_bn[0][0]         
                                                                 add_31[0][0]                     
__________________________________________________________________________________________________
block6_sepconv1_act (Activation (None, 14, 14, 728)  0           add_32[0][0]                     
__________________________________________________________________________________________________
block6_sepconv1 (SeparableConv2 (None, 14, 14, 728)  536536      block6_sepconv1_act[0][0]        
__________________________________________________________________________________________________
block6_sepconv1_bn (BatchNormal (None, 14, 14, 728)  2912        block6_sepconv1[0][0]            
__________________________________________________________________________________________________
block6_sepconv2_act (Activation (None, 14, 14, 728)  0           block6_sepconv1_bn[0][0]         
__________________________________________________________________________________________________
block6_sepconv2 (SeparableConv2 (None, 14, 14, 728)  536536      block6_sepconv2_act[0][0]        
__________________________________________________________________________________________________
block6_sepconv2_bn (BatchNormal (None, 14, 14, 728)  2912        block6_sepconv2[0][0]            
__________________________________________________________________________________________________
block6_sepconv3_act (Activation (None, 14, 14, 728)  0           block6_sepconv2_bn[0][0]         
__________________________________________________________________________________________________
block6_sepconv3 (SeparableConv2 (None, 14, 14, 728)  536536      block6_sepconv3_act[0][0]        
__________________________________________________________________________________________________
block6_sepconv3_bn (BatchNormal (None, 14, 14, 728)  2912        block6_sepconv3[0][0]            
__________________________________________________________________________________________________
add_33 (Add)                    (None, 14, 14, 728)  0           block6_sepconv3_bn[0][0]         
                                                                 add_32[0][0]                     
__________________________________________________________________________________________________
block7_sepconv1_act (Activation (None, 14, 14, 728)  0           add_33[0][0]                     
__________________________________________________________________________________________________
block7_sepconv1 (SeparableConv2 (None, 14, 14, 728)  536536      block7_sepconv1_act[0][0]        
__________________________________________________________________________________________________
block7_sepconv1_bn (BatchNormal (None, 14, 14, 728)  2912        block7_sepconv1[0][0]            
__________________________________________________________________________________________________
block7_sepconv2_act (Activation (None, 14, 14, 728)  0           block7_sepconv1_bn[0][0]         
__________________________________________________________________________________________________
block7_sepconv2 (SeparableConv2 (None, 14, 14, 728)  536536      block7_sepconv2_act[0][0]        
__________________________________________________________________________________________________
block7_sepconv2_bn (BatchNormal (None, 14, 14, 728)  2912        block7_sepconv2[0][0]            
__________________________________________________________________________________________________
block7_sepconv3_act (Activation (None, 14, 14, 728)  0           block7_sepconv2_bn[0][0]         
__________________________________________________________________________________________________
block7_sepconv3 (SeparableConv2 (None, 14, 14, 728)  536536      block7_sepconv3_act[0][0]        
__________________________________________________________________________________________________
block7_sepconv3_bn (BatchNormal (None, 14, 14, 728)  2912        block7_sepconv3[0][0]            
__________________________________________________________________________________________________
add_34 (Add)                    (None, 14, 14, 728)  0           block7_sepconv3_bn[0][0]         
                                                                 add_33[0][0]                     
__________________________________________________________________________________________________
block8_sepconv1_act (Activation (None, 14, 14, 728)  0           add_34[0][0]                     
__________________________________________________________________________________________________
block8_sepconv1 (SeparableConv2 (None, 14, 14, 728)  536536      block8_sepconv1_act[0][0]        
__________________________________________________________________________________________________
block8_sepconv1_bn (BatchNormal (None, 14, 14, 728)  2912        block8_sepconv1[0][0]            
__________________________________________________________________________________________________
block8_sepconv2_act (Activation (None, 14, 14, 728)  0           block8_sepconv1_bn[0][0]         
__________________________________________________________________________________________________
block8_sepconv2 (SeparableConv2 (None, 14, 14, 728)  536536      block8_sepconv2_act[0][0]        
__________________________________________________________________________________________________
block8_sepconv2_bn (BatchNormal (None, 14, 14, 728)  2912        block8_sepconv2[0][0]            
__________________________________________________________________________________________________
block8_sepconv3_act (Activation (None, 14, 14, 728)  0           block8_sepconv2_bn[0][0]         
__________________________________________________________________________________________________
block8_sepconv3 (SeparableConv2 (None, 14, 14, 728)  536536      block8_sepconv3_act[0][0]        
__________________________________________________________________________________________________
block8_sepconv3_bn (BatchNormal (None, 14, 14, 728)  2912        block8_sepconv3[0][0]            
__________________________________________________________________________________________________
add_35 (Add)                    (None, 14, 14, 728)  0           block8_sepconv3_bn[0][0]         
                                                                 add_34[0][0]                     
__________________________________________________________________________________________________
block9_sepconv1_act (Activation (None, 14, 14, 728)  0           add_35[0][0]                     
__________________________________________________________________________________________________
block9_sepconv1 (SeparableConv2 (None, 14, 14, 728)  536536      block9_sepconv1_act[0][0]        
__________________________________________________________________________________________________
block9_sepconv1_bn (BatchNormal (None, 14, 14, 728)  2912        block9_sepconv1[0][0]            
__________________________________________________________________________________________________
block9_sepconv2_act (Activation (None, 14, 14, 728)  0           block9_sepconv1_bn[0][0]         
__________________________________________________________________________________________________
block9_sepconv2 (SeparableConv2 (None, 14, 14, 728)  536536      block9_sepconv2_act[0][0]        
__________________________________________________________________________________________________
block9_sepconv2_bn (BatchNormal (None, 14, 14, 728)  2912        block9_sepconv2[0][0]            
__________________________________________________________________________________________________
block9_sepconv3_act (Activation (None, 14, 14, 728)  0           block9_sepconv2_bn[0][0]         
__________________________________________________________________________________________________
block9_sepconv3 (SeparableConv2 (None, 14, 14, 728)  536536      block9_sepconv3_act[0][0]        
__________________________________________________________________________________________________
block9_sepconv3_bn (BatchNormal (None, 14, 14, 728)  2912        block9_sepconv3[0][0]            
__________________________________________________________________________________________________
add_36 (Add)                    (None, 14, 14, 728)  0           block9_sepconv3_bn[0][0]         
                                                                 add_35[0][0]                     
__________________________________________________________________________________________________
block10_sepconv1_act (Activatio (None, 14, 14, 728)  0           add_36[0][0]                     
__________________________________________________________________________________________________
block10_sepconv1 (SeparableConv (None, 14, 14, 728)  536536      block10_sepconv1_act[0][0]       
__________________________________________________________________________________________________
block10_sepconv1_bn (BatchNorma (None, 14, 14, 728)  2912        block10_sepconv1[0][0]           
__________________________________________________________________________________________________
block10_sepconv2_act (Activatio (None, 14, 14, 728)  0           block10_sepconv1_bn[0][0]        
__________________________________________________________________________________________________
block10_sepconv2 (SeparableConv (None, 14, 14, 728)  536536      block10_sepconv2_act[0][0]       
__________________________________________________________________________________________________
block10_sepconv2_bn (BatchNorma (None, 14, 14, 728)  2912        block10_sepconv2[0][0]           
__________________________________________________________________________________________________
block10_sepconv3_act (Activatio (None, 14, 14, 728)  0           block10_sepconv2_bn[0][0]        
__________________________________________________________________________________________________
block10_sepconv3 (SeparableConv (None, 14, 14, 728)  536536      block10_sepconv3_act[0][0]       
__________________________________________________________________________________________________
block10_sepconv3_bn (BatchNorma (None, 14, 14, 728)  2912        block10_sepconv3[0][0]           
__________________________________________________________________________________________________
add_37 (Add)                    (None, 14, 14, 728)  0           block10_sepconv3_bn[0][0]        
                                                                 add_36[0][0]                     
__________________________________________________________________________________________________
block11_sepconv1_act (Activatio (None, 14, 14, 728)  0           add_37[0][0]                     
__________________________________________________________________________________________________
block11_sepconv1 (SeparableConv (None, 14, 14, 728)  536536      block11_sepconv1_act[0][0]       
__________________________________________________________________________________________________
block11_sepconv1_bn (BatchNorma (None, 14, 14, 728)  2912        block11_sepconv1[0][0]           
__________________________________________________________________________________________________
block11_sepconv2_act (Activatio (None, 14, 14, 728)  0           block11_sepconv1_bn[0][0]        
__________________________________________________________________________________________________
block11_sepconv2 (SeparableConv (None, 14, 14, 728)  536536      block11_sepconv2_act[0][0]       
__________________________________________________________________________________________________
block11_sepconv2_bn (BatchNorma (None, 14, 14, 728)  2912        block11_sepconv2[0][0]           
__________________________________________________________________________________________________
block11_sepconv3_act (Activatio (None, 14, 14, 728)  0           block11_sepconv2_bn[0][0]        
__________________________________________________________________________________________________
block11_sepconv3 (SeparableConv (None, 14, 14, 728)  536536      block11_sepconv3_act[0][0]       
__________________________________________________________________________________________________
block11_sepconv3_bn (BatchNorma (None, 14, 14, 728)  2912        block11_sepconv3[0][0]           
__________________________________________________________________________________________________
add_38 (Add)                    (None, 14, 14, 728)  0           block11_sepconv3_bn[0][0]        
                                                                 add_37[0][0]                     
__________________________________________________________________________________________________
block12_sepconv1_act (Activatio (None, 14, 14, 728)  0           add_38[0][0]                     
__________________________________________________________________________________________________
block12_sepconv1 (SeparableConv (None, 14, 14, 728)  536536      block12_sepconv1_act[0][0]       
__________________________________________________________________________________________________
block12_sepconv1_bn (BatchNorma (None, 14, 14, 728)  2912        block12_sepconv1[0][0]           
__________________________________________________________________________________________________
block12_sepconv2_act (Activatio (None, 14, 14, 728)  0           block12_sepconv1_bn[0][0]        
__________________________________________________________________________________________________
block12_sepconv2 (SeparableConv (None, 14, 14, 728)  536536      block12_sepconv2_act[0][0]       
__________________________________________________________________________________________________
block12_sepconv2_bn (BatchNorma (None, 14, 14, 728)  2912        block12_sepconv2[0][0]           
__________________________________________________________________________________________________
block12_sepconv3_act (Activatio (None, 14, 14, 728)  0           block12_sepconv2_bn[0][0]        
__________________________________________________________________________________________________
block12_sepconv3 (SeparableConv (None, 14, 14, 728)  536536      block12_sepconv3_act[0][0]       
__________________________________________________________________________________________________
block12_sepconv3_bn (BatchNorma (None, 14, 14, 728)  2912        block12_sepconv3[0][0]           
__________________________________________________________________________________________________
add_39 (Add)                    (None, 14, 14, 728)  0           block12_sepconv3_bn[0][0]        
                                                                 add_38[0][0]                     
__________________________________________________________________________________________________
block13_sepconv1_act (Activatio (None, 14, 14, 728)  0           add_39[0][0]                     
__________________________________________________________________________________________________
block13_sepconv1 (SeparableConv (None, 14, 14, 728)  536536      block13_sepconv1_act[0][0]       
__________________________________________________________________________________________________
block13_sepconv1_bn (BatchNorma (None, 14, 14, 728)  2912        block13_sepconv1[0][0]           
__________________________________________________________________________________________________
block13_sepconv2_act (Activatio (None, 14, 14, 728)  0           block13_sepconv1_bn[0][0]        
__________________________________________________________________________________________________
block13_sepconv2 (SeparableConv (None, 14, 14, 1024) 752024      block13_sepconv2_act[0][0]       
__________________________________________________________________________________________________
block13_sepconv2_bn (BatchNorma (None, 14, 14, 1024) 4096        block13_sepconv2[0][0]           
__________________________________________________________________________________________________
conv2d_14 (Conv2D)              (None, 7, 7, 1024)   745472      add_39[0][0]                     
__________________________________________________________________________________________________
block13_pool (MaxPooling2D)     (None, 7, 7, 1024)   0           block13_sepconv2_bn[0][0]        
__________________________________________________________________________________________________
batch_normalization_8 (BatchNor (None, 7, 7, 1024)   4096        conv2d_14[0][0]                  
__________________________________________________________________________________________________
add_40 (Add)                    (None, 7, 7, 1024)   0           block13_pool[0][0]               
                                                                 batch_normalization_8[0][0]      
__________________________________________________________________________________________________
block14_sepconv1 (SeparableConv (None, 7, 7, 1536)   1582080     add_40[0][0]                     
__________________________________________________________________________________________________
block14_sepconv1_bn (BatchNorma (None, 7, 7, 1536)   6144        block14_sepconv1[0][0]           
__________________________________________________________________________________________________
block14_sepconv1_act (Activatio (None, 7, 7, 1536)   0           block14_sepconv1_bn[0][0]        
__________________________________________________________________________________________________
block14_sepconv2 (SeparableConv (None, 7, 7, 2048)   3159552     block14_sepconv1_act[0][0]       
__________________________________________________________________________________________________
block14_sepconv2_bn (BatchNorma (None, 7, 7, 2048)   8192        block14_sepconv2[0][0]           
__________________________________________________________________________________________________
block14_sepconv2_act (Activatio (None, 7, 7, 2048)   0           block14_sepconv2_bn[0][0]        
__________________________________________________________________________________________________
global_average_pooling2d_2 (Glo (None, 2048)         0           block14_sepconv2_act[0][0]       
__________________________________________________________________________________________________
dense_4 (Dense)                 (None, 133)          272517      global_average_pooling2d_2[0][0] 
==================================================================================================
Total params: 21,133,997
Trainable params: 21,079,469
Non-trainable params: 54,528
__________________________________________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [20]:
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [25]:
### TODO: Train the model.

datagen_train = ImageDataGenerator(
    width_shift_range=0.1,
    height_shift_range=0.1,
    horizontal_flip=True)

datagen_valid = ImageDataGenerator(
    width_shift_range=0.1,
    height_shift_range=0.1,
    horizontal_flip=True)

# for batch_size in (list(range(25, 1, -5)) + [1]):
#     model.fit(train_tensors, train_targets, 
#               validation_data=(valid_tensors, valid_targets),
#               epochs=3, batch_size=batch_size, callbacks=[checkpointer], verbose=1)

# model.fit(train_tensors, train_targets, 
#           validation_data=(valid_tensors, valid_targets),
#           epochs=5, batch_size=1, callbacks=[checkpointer], verbose=1)
batch_size = 16

model.fit_generator(datagen_train.flow(train_tensors, train_targets, batch_size=batch_size),
                 steps_per_epoch=train_tensors.shape[0] // batch_size,
                 epochs=100, verbose=2, callbacks=[checkpointer],
                 validation_data=datagen_valid.flow(valid_tensors, valid_targets, batch_size=batch_size),
                 validation_steps=valid_tensors.shape[0] // batch_size)
Epoch 1/100
 - 197s - loss: 1.0715 - acc: 0.6800 - val_loss: 2.3749 - val_acc: 0.5653

Epoch 00001: val_loss did not improve from 1.79609
Epoch 2/100
 - 198s - loss: 0.8864 - acc: 0.7251 - val_loss: 1.8539 - val_acc: 0.5976

Epoch 00002: val_loss did not improve from 1.79609
Epoch 3/100
 - 199s - loss: 0.7315 - acc: 0.7782 - val_loss: 1.6967 - val_acc: 0.6132

Epoch 00003: val_loss improved from 1.79609 to 1.69673, saving model to saved_models/weights.best.final_model.hdf5
Epoch 4/100
 - 199s - loss: 0.6280 - acc: 0.8028 - val_loss: 2.2142 - val_acc: 0.5976

Epoch 00004: val_loss did not improve from 1.69673
Epoch 5/100
 - 199s - loss: 0.5567 - acc: 0.8227 - val_loss: 1.6348 - val_acc: 0.6671

Epoch 00005: val_loss improved from 1.69673 to 1.63478, saving model to saved_models/weights.best.final_model.hdf5
Epoch 6/100
 - 199s - loss: 0.4911 - acc: 0.8483 - val_loss: 2.6851 - val_acc: 0.6012

Epoch 00006: val_loss did not improve from 1.63478
Epoch 7/100
 - 199s - loss: 0.4537 - acc: 0.8588 - val_loss: 2.7503 - val_acc: 0.5856

Epoch 00007: val_loss did not improve from 1.63478
Epoch 8/100
 - 199s - loss: 0.3986 - acc: 0.8751 - val_loss: 3.4494 - val_acc: 0.5713

Epoch 00008: val_loss did not improve from 1.63478
Epoch 9/100
 - 199s - loss: 0.3763 - acc: 0.8874 - val_loss: 3.4716 - val_acc: 0.5892

Epoch 00009: val_loss did not improve from 1.63478
Epoch 10/100
 - 199s - loss: 0.3613 - acc: 0.8862 - val_loss: 1.6989 - val_acc: 0.6802

Epoch 00010: val_loss did not improve from 1.63478
Epoch 11/100
 - 199s - loss: 0.3153 - acc: 0.9026 - val_loss: 1.7874 - val_acc: 0.7042

Epoch 00011: val_loss did not improve from 1.63478
Epoch 12/100
 - 199s - loss: 0.3080 - acc: 0.9062 - val_loss: 2.6410 - val_acc: 0.6359

Epoch 00012: val_loss did not improve from 1.63478
Epoch 13/100
 - 199s - loss: 0.2888 - acc: 0.9122 - val_loss: 2.0701 - val_acc: 0.6647

Epoch 00013: val_loss did not improve from 1.63478
Epoch 14/100
 - 199s - loss: 0.2756 - acc: 0.9179 - val_loss: 2.4055 - val_acc: 0.6431

Epoch 00014: val_loss did not improve from 1.63478
Epoch 15/100
 - 199s - loss: 0.2621 - acc: 0.9231 - val_loss: 2.3003 - val_acc: 0.6778

Epoch 00015: val_loss did not improve from 1.63478
Epoch 16/100
 - 199s - loss: 0.2302 - acc: 0.9290 - val_loss: 1.7857 - val_acc: 0.6826

Epoch 00016: val_loss did not improve from 1.63478
Epoch 17/100
 - 199s - loss: 0.2406 - acc: 0.9305 - val_loss: 2.5236 - val_acc: 0.6731

Epoch 00017: val_loss did not improve from 1.63478
Epoch 18/100
 - 199s - loss: 0.2340 - acc: 0.9299 - val_loss: 2.6037 - val_acc: 0.6754

Epoch 00018: val_loss did not improve from 1.63478
Epoch 19/100
 - 199s - loss: 0.2135 - acc: 0.9371 - val_loss: 1.7722 - val_acc: 0.7162

Epoch 00019: val_loss did not improve from 1.63478
Epoch 20/100
 - 199s - loss: 0.2134 - acc: 0.9350 - val_loss: 2.2170 - val_acc: 0.7210

Epoch 00020: val_loss did not improve from 1.63478
Epoch 21/100
 - 199s - loss: 0.1899 - acc: 0.9430 - val_loss: 2.3532 - val_acc: 0.6994

Epoch 00021: val_loss did not improve from 1.63478
Epoch 22/100
 - 199s - loss: 0.2046 - acc: 0.9424 - val_loss: 2.9164 - val_acc: 0.6671

Epoch 00022: val_loss did not improve from 1.63478
Epoch 23/100
 - 199s - loss: 0.1737 - acc: 0.9472 - val_loss: 1.7194 - val_acc: 0.7401

Epoch 00023: val_loss did not improve from 1.63478
Epoch 24/100
 - 199s - loss: 0.1753 - acc: 0.9460 - val_loss: 2.5078 - val_acc: 0.6719

Epoch 00024: val_loss did not improve from 1.63478
Epoch 25/100
 - 199s - loss: 0.1682 - acc: 0.9502 - val_loss: 1.8512 - val_acc: 0.6886

Epoch 00025: val_loss did not improve from 1.63478
Epoch 26/100
 - 199s - loss: 0.1601 - acc: 0.9547 - val_loss: 1.9843 - val_acc: 0.7222

Epoch 00026: val_loss did not improve from 1.63478
Epoch 27/100
 - 199s - loss: 0.1553 - acc: 0.9531 - val_loss: 2.2239 - val_acc: 0.6862

Epoch 00027: val_loss did not improve from 1.63478
Epoch 28/100
 - 199s - loss: 0.1500 - acc: 0.9558 - val_loss: 1.8953 - val_acc: 0.7377

Epoch 00028: val_loss did not improve from 1.63478
Epoch 29/100
 - 199s - loss: 0.1505 - acc: 0.9586 - val_loss: 1.7667 - val_acc: 0.7078

Epoch 00029: val_loss did not improve from 1.63478
Epoch 30/100
 - 199s - loss: 0.1477 - acc: 0.9571 - val_loss: 2.1758 - val_acc: 0.6994

Epoch 00030: val_loss did not improve from 1.63478
Epoch 31/100
 - 199s - loss: 0.1360 - acc: 0.9603 - val_loss: 1.8870 - val_acc: 0.7305

Epoch 00031: val_loss did not improve from 1.63478
Epoch 32/100
 - 199s - loss: 0.1439 - acc: 0.9603 - val_loss: 2.4415 - val_acc: 0.7018

Epoch 00032: val_loss did not improve from 1.63478
Epoch 33/100
 - 199s - loss: 0.1385 - acc: 0.9594 - val_loss: 1.6209 - val_acc: 0.7114

Epoch 00033: val_loss improved from 1.63478 to 1.62086, saving model to saved_models/weights.best.final_model.hdf5
Epoch 34/100
 - 199s - loss: 0.1407 - acc: 0.9568 - val_loss: 2.7123 - val_acc: 0.6802

Epoch 00034: val_loss did not improve from 1.62086
Epoch 35/100
 - 199s - loss: 0.1249 - acc: 0.9604 - val_loss: 1.8556 - val_acc: 0.7198

Epoch 00035: val_loss did not improve from 1.62086
Epoch 36/100
 - 199s - loss: 0.1322 - acc: 0.9612 - val_loss: 2.6408 - val_acc: 0.6635

Epoch 00036: val_loss did not improve from 1.62086
Epoch 37/100
 - 199s - loss: 0.1206 - acc: 0.9649 - val_loss: 2.0912 - val_acc: 0.7222

Epoch 00037: val_loss did not improve from 1.62086
Epoch 38/100
 - 199s - loss: 0.1268 - acc: 0.9630 - val_loss: 2.1801 - val_acc: 0.7066

Epoch 00038: val_loss did not improve from 1.62086
Epoch 39/100
 - 199s - loss: 0.1307 - acc: 0.9654 - val_loss: 2.9745 - val_acc: 0.6647

Epoch 00039: val_loss did not improve from 1.62086
Epoch 40/100
 - 199s - loss: 0.1253 - acc: 0.9645 - val_loss: 1.5710 - val_acc: 0.7497

Epoch 00040: val_loss improved from 1.62086 to 1.57101, saving model to saved_models/weights.best.final_model.hdf5
Epoch 41/100
 - 199s - loss: 0.1103 - acc: 0.9667 - val_loss: 1.9471 - val_acc: 0.7353

Epoch 00041: val_loss did not improve from 1.57101
Epoch 42/100
 - 199s - loss: 0.1228 - acc: 0.9655 - val_loss: 2.3034 - val_acc: 0.7162

Epoch 00042: val_loss did not improve from 1.57101
Epoch 43/100
 - 199s - loss: 0.1104 - acc: 0.9672 - val_loss: 2.6420 - val_acc: 0.7054

Epoch 00043: val_loss did not improve from 1.57101
Epoch 44/100
 - 199s - loss: 0.1081 - acc: 0.9694 - val_loss: 2.2457 - val_acc: 0.6850

Epoch 00044: val_loss did not improve from 1.57101
Epoch 45/100
 - 199s - loss: 0.1166 - acc: 0.9655 - val_loss: 2.5106 - val_acc: 0.6862

Epoch 00045: val_loss did not improve from 1.57101
Epoch 46/100
 - 199s - loss: 0.0958 - acc: 0.9714 - val_loss: 1.8431 - val_acc: 0.7365

Epoch 00046: val_loss did not improve from 1.57101
Epoch 47/100
 - 199s - loss: 0.0955 - acc: 0.9724 - val_loss: 2.2369 - val_acc: 0.6850

Epoch 00047: val_loss did not improve from 1.57101
Epoch 48/100
 - 199s - loss: 0.1227 - acc: 0.9645 - val_loss: 2.2577 - val_acc: 0.7365

Epoch 00048: val_loss did not improve from 1.57101
Epoch 49/100
 - 199s - loss: 0.0917 - acc: 0.9724 - val_loss: 2.3156 - val_acc: 0.7054

Epoch 00049: val_loss did not improve from 1.57101
Epoch 50/100
 - 199s - loss: 0.1062 - acc: 0.9685 - val_loss: 2.0780 - val_acc: 0.7293

Epoch 00050: val_loss did not improve from 1.57101
Epoch 51/100
 - 199s - loss: 0.1005 - acc: 0.9732 - val_loss: 3.3128 - val_acc: 0.6383

Epoch 00051: val_loss did not improve from 1.57101
Epoch 52/100
 - 199s - loss: 0.0952 - acc: 0.9735 - val_loss: 2.4391 - val_acc: 0.6994

Epoch 00052: val_loss did not improve from 1.57101
Epoch 53/100
 - 199s - loss: 0.1103 - acc: 0.9702 - val_loss: 2.0044 - val_acc: 0.7281

Epoch 00053: val_loss did not improve from 1.57101
Epoch 54/100
 - 199s - loss: 0.0895 - acc: 0.9750 - val_loss: 2.7961 - val_acc: 0.7222

Epoch 00054: val_loss did not improve from 1.57101
Epoch 55/100
 - 199s - loss: 0.0956 - acc: 0.9732 - val_loss: 3.6639 - val_acc: 0.6575

Epoch 00055: val_loss did not improve from 1.57101
Epoch 56/100
 - 199s - loss: 0.0870 - acc: 0.9744 - val_loss: 2.3004 - val_acc: 0.7365

Epoch 00056: val_loss did not improve from 1.57101
Epoch 57/100
 - 199s - loss: 0.0871 - acc: 0.9732 - val_loss: 2.2714 - val_acc: 0.7222

Epoch 00057: val_loss did not improve from 1.57101
Epoch 58/100
 - 199s - loss: 0.0938 - acc: 0.9732 - val_loss: 2.4657 - val_acc: 0.7234

Epoch 00058: val_loss did not improve from 1.57101
Epoch 59/100
 - 199s - loss: 0.0882 - acc: 0.9751 - val_loss: 2.4433 - val_acc: 0.7090

Epoch 00059: val_loss did not improve from 1.57101
Epoch 60/100
 - 199s - loss: 0.0954 - acc: 0.9726 - val_loss: 2.2645 - val_acc: 0.7126

Epoch 00060: val_loss did not improve from 1.57101
Epoch 61/100
 - 199s - loss: 0.0805 - acc: 0.9768 - val_loss: 2.0182 - val_acc: 0.7437

Epoch 00061: val_loss did not improve from 1.57101
Epoch 62/100
 - 199s - loss: 0.0892 - acc: 0.9766 - val_loss: 2.1163 - val_acc: 0.7317

Epoch 00062: val_loss did not improve from 1.57101
Epoch 63/100
 - 199s - loss: 0.0832 - acc: 0.9763 - val_loss: 2.0607 - val_acc: 0.7126

Epoch 00063: val_loss did not improve from 1.57101
Epoch 64/100
 - 199s - loss: 0.0671 - acc: 0.9801 - val_loss: 2.7135 - val_acc: 0.6814

Epoch 00064: val_loss did not improve from 1.57101
Epoch 65/100
 - 199s - loss: 0.0799 - acc: 0.9775 - val_loss: 1.8797 - val_acc: 0.7485

Epoch 00065: val_loss did not improve from 1.57101
Epoch 66/100
 - 199s - loss: 0.0842 - acc: 0.9772 - val_loss: 2.2495 - val_acc: 0.7425

Epoch 00066: val_loss did not improve from 1.57101
Epoch 67/100
 - 199s - loss: 0.0792 - acc: 0.9768 - val_loss: 2.0970 - val_acc: 0.7449

Epoch 00067: val_loss did not improve from 1.57101
Epoch 68/100
 - 199s - loss: 0.0804 - acc: 0.9757 - val_loss: 1.5485 - val_acc: 0.7617

Epoch 00068: val_loss improved from 1.57101 to 1.54853, saving model to saved_models/weights.best.final_model.hdf5
Epoch 69/100
 - 199s - loss: 0.1014 - acc: 0.9739 - val_loss: 2.4916 - val_acc: 0.7186

Epoch 00069: val_loss did not improve from 1.54853
Epoch 70/100
 - 199s - loss: 0.0719 - acc: 0.9781 - val_loss: 1.9787 - val_acc: 0.7329

Epoch 00070: val_loss did not improve from 1.54853
Epoch 71/100
 - 199s - loss: 0.0729 - acc: 0.9802 - val_loss: 2.3393 - val_acc: 0.7054

Epoch 00071: val_loss did not improve from 1.54853
Epoch 72/100
 - 199s - loss: 0.0696 - acc: 0.9802 - val_loss: 2.1073 - val_acc: 0.7246

Epoch 00072: val_loss did not improve from 1.54853
Epoch 73/100
 - 199s - loss: 0.0701 - acc: 0.9799 - val_loss: 2.3433 - val_acc: 0.6958

Epoch 00073: val_loss did not improve from 1.54853
Epoch 74/100
 - 199s - loss: 0.0692 - acc: 0.9798 - val_loss: 2.2498 - val_acc: 0.7497

Epoch 00074: val_loss did not improve from 1.54853
Epoch 75/100
 - 199s - loss: 0.0795 - acc: 0.9768 - val_loss: 2.0088 - val_acc: 0.7317

Epoch 00075: val_loss did not improve from 1.54853
Epoch 76/100
 - 199s - loss: 0.0822 - acc: 0.9787 - val_loss: 1.9938 - val_acc: 0.7257

Epoch 00076: val_loss did not improve from 1.54853
Epoch 77/100
 - 199s - loss: 0.0795 - acc: 0.9795 - val_loss: 2.0758 - val_acc: 0.7210

Epoch 00077: val_loss did not improve from 1.54853
Epoch 78/100
 - 199s - loss: 0.0523 - acc: 0.9850 - val_loss: 2.1801 - val_acc: 0.7401

Epoch 00078: val_loss did not improve from 1.54853
Epoch 79/100
 - 199s - loss: 0.0694 - acc: 0.9816 - val_loss: 2.7399 - val_acc: 0.7210

Epoch 00079: val_loss did not improve from 1.54853
Epoch 80/100
 - 199s - loss: 0.0701 - acc: 0.9804 - val_loss: 2.5401 - val_acc: 0.7198

Epoch 00080: val_loss did not improve from 1.54853
Epoch 81/100
 - 199s - loss: 0.0754 - acc: 0.9796 - val_loss: 1.7178 - val_acc: 0.7305

Epoch 00081: val_loss did not improve from 1.54853
Epoch 82/100
 - 199s - loss: 0.0599 - acc: 0.9828 - val_loss: 2.5700 - val_acc: 0.7341

Epoch 00082: val_loss did not improve from 1.54853
Epoch 83/100
 - 199s - loss: 0.0766 - acc: 0.9799 - val_loss: 2.7136 - val_acc: 0.7090

Epoch 00083: val_loss did not improve from 1.54853
Epoch 84/100
 - 199s - loss: 0.0635 - acc: 0.9841 - val_loss: 2.1575 - val_acc: 0.7341

Epoch 00084: val_loss did not improve from 1.54853
Epoch 85/100
 - 199s - loss: 0.0697 - acc: 0.9807 - val_loss: 2.2098 - val_acc: 0.7329

Epoch 00085: val_loss did not improve from 1.54853
Epoch 86/100
 - 199s - loss: 0.0665 - acc: 0.9805 - val_loss: 2.0156 - val_acc: 0.7413

Epoch 00086: val_loss did not improve from 1.54853
Epoch 87/100
 - 199s - loss: 0.0645 - acc: 0.9822 - val_loss: 2.4687 - val_acc: 0.7210

Epoch 00087: val_loss did not improve from 1.54853
Epoch 88/100
 - 199s - loss: 0.0626 - acc: 0.9823 - val_loss: 2.6486 - val_acc: 0.7102

Epoch 00088: val_loss did not improve from 1.54853
Epoch 89/100
 - 199s - loss: 0.0621 - acc: 0.9816 - val_loss: 2.3206 - val_acc: 0.7509

Epoch 00089: val_loss did not improve from 1.54853
Epoch 90/100
 - 199s - loss: 0.0647 - acc: 0.9828 - val_loss: 2.3188 - val_acc: 0.7138

Epoch 00090: val_loss did not improve from 1.54853
Epoch 91/100
 - 199s - loss: 0.0620 - acc: 0.9817 - val_loss: 2.5624 - val_acc: 0.7246

Epoch 00091: val_loss did not improve from 1.54853
Epoch 92/100
 - 199s - loss: 0.0740 - acc: 0.9814 - val_loss: 2.3307 - val_acc: 0.7401

Epoch 00092: val_loss did not improve from 1.54853
Epoch 93/100
 - 199s - loss: 0.0566 - acc: 0.9852 - val_loss: 2.0789 - val_acc: 0.7377

Epoch 00093: val_loss did not improve from 1.54853
Epoch 94/100
 - 199s - loss: 0.0553 - acc: 0.9870 - val_loss: 2.2896 - val_acc: 0.7353

Epoch 00094: val_loss did not improve from 1.54853
Epoch 95/100
 - 199s - loss: 0.0645 - acc: 0.9822 - val_loss: 3.0221 - val_acc: 0.7090

Epoch 00095: val_loss did not improve from 1.54853
Epoch 96/100
 - 199s - loss: 0.0627 - acc: 0.9844 - val_loss: 2.1148 - val_acc: 0.7749

Epoch 00096: val_loss did not improve from 1.54853
Epoch 97/100
 - 199s - loss: 0.0634 - acc: 0.9808 - val_loss: 2.1616 - val_acc: 0.7281

Epoch 00097: val_loss did not improve from 1.54853
Epoch 98/100
 - 199s - loss: 0.0674 - acc: 0.9843 - val_loss: 2.6026 - val_acc: 0.7222

Epoch 00098: val_loss did not improve from 1.54853
Epoch 99/100
 - 199s - loss: 0.0704 - acc: 0.9804 - val_loss: 2.5132 - val_acc: 0.7257

Epoch 00099: val_loss did not improve from 1.54853
Epoch 100/100
 - 199s - loss: 0.0692 - acc: 0.9826 - val_loss: 2.3754 - val_acc: 0.7222

Epoch 00100: val_loss did not improve from 1.54853
Out[25]:
<keras.callbacks.History at 0x7fe1c2c4d438>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [26]:
### TODO: Load the model weights with the best validation loss.
model.load_weights('saved_models/weights.best.final_model.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [27]:
### TODO: Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
model_predictions = [np.argmax(model.predict(np.expand_dims(feature, axis=0))) for feature in test_tensors]

test_accuracy = 100*np.sum(np.array(model_predictions)==np.argmax(test_targets, axis=1))/len(model_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 73.5646%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [45]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from extract_bottleneck_features import *

def predict_breed(img_path):
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    # return np.expand_dims(x, axis=0)
    tensor = np.expand_dims(x, axis=0).astype('float32')/255
    # obtain predicted vector
    predicted_vector = model.predict(tensor)
    # return dog breed that is predicted by the model
    n = np.argmax(predicted_vector)
    dog_breed = dog_names[n]
    breed_path = "dogImages/test/" + ("%03d" % (n+1,)) + "." + dog_breed + "/*"
    img_files = np.array(glob(breed_path))
    return (dog_breed, img_files[0])

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [49]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def find_breed(img_path):
    # extract pre-trained face detector
    face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

    # load color (BGR) image
    img = cv2.imread(img_path)
    # convert BGR image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # find faces in image
    faces = face_cascade.detectMultiScale(gray)
    dogs = dog_detector(img_path)

    if len(faces) > 0 or dogs:
        if len(faces) != 0:
            # get bounding box for each detected face
            for (x,y,w,h) in faces:
                # add bounding box to color image
                cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

            # convert BGR image to RGB for plotting
            cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

            # display the image, along with bounding box
            plt.imshow(cv_rgb)
            plt.show()
            breed_name, breed_path = predict_breed(img_path)
            print('Number of human faces in the picture {} detected: {}'.format(img_path, str(len(faces))))
            print("Human in the picture {} resembles {}".format(img_path, breed_name))
            
            # Show image of resembling dog
            img = cv2.imread(breed_path)
            cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            plt.imshow(cv_rgb)
            plt.show()
    
        if dogs:
            # Show input image
            img = cv2.imread(img_path)
            cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            plt.imshow(cv_rgb)
            plt.show()

            breed_name, breed_path = predict_breed(img_path)
            print("Dog in the picture '{}' is {}".format(img_path, breed_name))
            
            # Show image of detected dog
            img = cv2.imread(breed_path)
            cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            plt.imshow(cv_rgb)
            plt.show()
        
    else:
        img = cv2.imread(img_path)
        cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.imshow(cv_rgb)
        plt.show()
        print("Error: No human or dog was detected in the picture {}.".format(img_path))
        
img_files = np.array(glob("images/*"))

for img in img_files:
    find_breed(img)
dogImages/test/055.Curly-coated_retriever/*
Dog in the picture 'images/American_water_spaniel_00648.jpg' is Curly-coated_retriever
dogImages/test/091.Japanese_chin/*
Number of human faces in the picture images/sample_human_output.png detected: 1
Human in the picture images/sample_human_output.png resembles Japanese_chin
dogImages/test/096.Labrador_retriever/*
Dog in the picture 'images/Labrador_retriever_06449.jpg' is Labrador_retriever
dogImages/test/037.Brittany/*
Dog in the picture 'images/Brittany_02625.jpg' is Brittany
dogImages/test/047.Chesapeake_bay_retriever/*
Dog in the picture 'images/Labrador_retriever_06455.jpg' is Chesapeake_bay_retriever
Error: No human or dog was detected in the picture images/sample_cnn.png.
dogImages/test/096.Labrador_retriever/*
Dog in the picture 'images/Labrador_retriever_06457.jpg' is Labrador_retriever
dogImages/test/055.Curly-coated_retriever/*
Dog in the picture 'images/Curly-coated_retriever_03896.jpg' is Curly-coated_retriever
Error: No human or dog was detected in the picture images/sample_dog_output.png.
dogImages/test/130.Welsh_springer_spaniel/*
Dog in the picture 'images/Welsh_springer_spaniel_08203.jpg' is Welsh_springer_spaniel

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: I am quite happy with the results. For the most part people remind me of the dogs in the picture. Some breeds are incorrectly classified but they remind me of the dog they were classified as.

  • I think that neural-network learning would be more stable if I could change batch_size parameter more. I couldn't change this parameter much because of limited memory on my graphics card.

  • It would be interesting if the neural network was able to generate dog picture out of human. Similarly, to the lecture example of deep dream generator.

  • Currently I am showing first picture from test dog breed pictures corresponding to the detected breed. It would be interesting to find picture with most similarity out of all breed pictures and show that one. It would be funny.

In [54]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
img_files = np.array(glob("test/*"))

for img in img_files:
    find_breed(img)
dogImages/test/049.Chinese_crested/*
Number of human faces in the picture test/zena2.jpg detected: 1
Human in the picture test/zena2.jpg resembles Chinese_crested
dogImages/test/014.Basenji/*
Number of human faces in the picture test/martin.jpg detected: 1
Human in the picture test/martin.jpg resembles Basenji
dogImages/test/132.Xoloitzcuintli/*
Number of human faces in the picture test/nada1.jpg detected: 1
Human in the picture test/nada1.jpg resembles Xoloitzcuintli
dogImages/test/102.Manchester_terrier/*
Number of human faces in the picture test/martin2.png detected: 1
Human in the picture test/martin2.png resembles Manchester_terrier
dogImages/test/009.American_water_spaniel/*
Number of human faces in the picture test/nada2.jpg detected: 2
Human in the picture test/nada2.jpg resembles American_water_spaniel
Error: No human or dog was detected in the picture test/seal.jpg.
dogImages/test/088.Irish_water_spaniel/*
Number of human faces in the picture test/matus.png detected: 1
Human in the picture test/matus.png resembles Irish_water_spaniel
dogImages/test/120.Pharaoh_hound/*
Number of human faces in the picture test/igor.png detected: 1
Human in the picture test/igor.png resembles Pharaoh_hound
Error: No human or dog was detected in the picture test/sheep.jpg.
dogImages/test/016.Beagle/*
Number of human faces in the picture test/zena1.jpg detected: 1
Human in the picture test/zena1.jpg resembles Beagle
dogImages/test/076.Golden_retriever/*
Dog in the picture 'test/800px-Golden_Retriever_medium-to-light-coat.jpg' is Golden_retriever
dogImages/test/014.Basenji/*
Number of human faces in the picture test/janci.png detected: 1
Human in the picture test/janci.png resembles Basenji
dogImages/test/078.Great_dane/*
Dog in the picture 'test/french_bulldog.jpg' is Great_dane